<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017\12\14 0014
 * Time: 20:34
 */
namespace cate_tree;

class CateTree{

    /**
     * 无限级分类树
     * @author 王柯 <wangke.email@foxmail.com>
     * @return array
     */
    public function create_tree($cateResult){
        return $this->sort($cateResult);
    }

    /**
     * 无限极分类排序
     * @author 王柯 <wangke.email@foxmail.com>
     * @return array
     */
    public function sort($ruleResult,$pid = 0,$level = 0){

        static $arr = array();
        foreach ($ruleResult as $k => $v) {
            if($v['pid'] == $pid){
                $v['level'] = $level;
                $arr[] = $v;
                $this->sort($ruleResult,$v['id'],$level + 1);
            }
        }
        return $arr;
    }

    /**
     * 获取子栏目id
     * @param obj object 实例化模型对象
     * @author 王柯 <wangke.email@foxmail.com>
     * @return array
     */
    public function children_id($cate_id,$obj){
        $data = $obj
            ->field('id,pid')
            ->select();
        return $this->_children_id($data,$cate_id);
    }

    /**
     * 递归处理
     * @author 王柯 <wangke.email@foxmail.com>
     * @return array
     */
    private function _children_id($data,$cate_id){
        static $arr = array();
        foreach ($data as $k => $v) {
            if($v['pid'] == $cate_id){
                $arr[] = $v['id'];
                $this->_children_id($data,$v['id']);
            }
        }

        return $arr;
    }

    /**
     * 处理栏目排序
     * @param obj object 实例化模型对象
     * @author 王柯 <wangke.email@foxmail.com>
     * @return void
     */
    public function cate_sort($data,$obj){
        foreach ($data['sort'] as $k => $v){
            $obj->update(['id' => $k,'sort' => $v]);
        }
    }
}